const Koa = require('koa');
const WebSocket = require('ws');
const app = new Koa();
const wss = new WebSocket.Server({ port: 9914 });
const config = require('./config');

const borderWidth = 0.8
const selectorHeightBorderWidth = 2 * 2 - 1;
const wh = selectorHeightBorderWidth - borderWidth // 假数据下使用(width-height)
const lt = borderWidth // 假数据下使用(left-top)

wss.on('connection', (ws,req) => {
  console.log('server connection');
  // console.log("user",wss.clients)
  //连接成功时，向每个用户发送一次数据
  //发送数据有两种type，sheet(区域)和data(数据),一起传
  wss.clients.forEach(function (client) {
    let arr = [
      {id:1,left:-0.8+lt,top:-0.8+lt,width:97.8+wh,height:22.8+wh},
      {id:2,left:-0.8+lt,top:124.2+lt,width:97.8+wh,height:22.8+wh},
    ]; //假数据
    let data = {data:config.loadData,sheet:arr};
    client.send(JSON.stringify(data));
  });
  // 异步发送数据
  setTimeout(() => {
    wss.clients.forEach(function (client) {
      let arr = [
        {id:1,left:-0.8+lt,top:-0.8+lt,width:97.8+wh,height:22.8+wh},
        {id:2,left:99.2+lt,top:124.2+lt,width:97.8+wh,height:22.8+wh},
      ]; //假数据
      let data = {data:config.loadData,sheet:arr};
      client.send(JSON.stringify(data));
    });
  }, 2000);

  ws.on('message', msg => {
    let res = msg.toString()
    console.log('server receive msg：', res);

  });
});

app.use(async ctx => {
  ctx.body = 'run...';
});

app.listen(9913); 